﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PDFDesign.Model;
using System;
using System.Net;
using System.Text;

namespace PDFDesign.Common
{
    /// <summary>
    /// 操作类
    /// </summary>
    public class Utils
    {
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <param name="success"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string json, out bool success)
        {
            try
            {
                success = true;
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception)
            {
                success = false;
                return default(T);
            }
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="o"></param>
        /// <param name="success"></param>
        /// <returns></returns>
        public static string Serialize(object o, out bool success)
        {
            try
            {
                success = true;
                return JsonConvert.SerializeObject(o);
            }
            catch (Exception)
            {
                success = false;
                return "";
            }
        }

        /// <summary>
        /// 格式化
        /// </summary>
        /// <param name="json"></param>
        /// <param name="format"></param>
        /// <param name="success"></param>
        /// <returns></returns>
        public static string Format(string json, bool format, out bool success)
        {
            var res = json;
            success = true;
            try
            {
                dynamic parsedJson = JsonConvert.DeserializeObject(json);
                res = JsonConvert.SerializeObject(parsedJson, format ? Formatting.Indented : Formatting.None);
            }
            catch
            {
                success = false;
            }
            return res;
        }

        /// <summary>
        /// HTTP POST
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postStr"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string HttpPost(string url, string postStr = "", Encoding encode = null)
        {
            var result = string.Empty;
            try
            {
                var webClient = new WebClient { Encoding = encode ?? Encoding.UTF8 };
                var sendData = Encoding.UTF8.GetBytes(postStr);
                webClient.Headers.Add("Content-Type", "application/json");
                webClient.Headers.Add("ContentLength", sendData.Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
                var readData = webClient.UploadData(url, "POST", sendData);
                result = Encoding.UTF8.GetString(readData);
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }

#if DEBUG
        public static readonly string Host = "http://127.0.0.1:1011/";
#else
        public static readonly string Host = "http://render.teemo.silkage.net/";
#endif

        /// <summary>
        /// 数据转换
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static ReportData Convert(string data)
        {
            ReportData ret = null;
            try
            {
                var obj = new JObject
                {
                    ["data"] = JToken.Parse(data)
                };
                var str = HttpPost($"{Host}convert", JsonConvert.SerializeObject(obj));
                var res = JsonConvert.DeserializeObject<RenderResult<ReportData>>(str);
                if (res.Success) ret = res.Data;
            }
            catch (Exception) { }
            return ret;
        }

        /// <summary>
        /// 提交任务
        /// </summary>
        /// <param name="data"></param>
        /// <param name="style"></param>
        /// <returns></returns>
        public static string Push(dynamic data, NewStyle style)
        {
            var key = "";
            try
            {
                var obj = new JObject
                {
                    ["data"] = JToken.FromObject(data),
                    ["style"] = JToken.FromObject(style),
                    ["type"] = "pdf"
                };
                var str = HttpPost($"{Host}push", JsonConvert.SerializeObject(obj));
                var res = JsonConvert.DeserializeObject<RenderResult<string>>(str);
                key = res.Data;
            }
            catch (Exception) { }
            return key;
        }
    }
}
